/*
 * Copyright (c) 2008-2013 Haulmont. All rights reserved.
 * Use is subject to license terms, see http://www.cuba-platform.com/license for details.
 */

package com.haulmont.asu.web.ui.create_blank_frame;

import com.haulmont.asu.entity.*;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.gui.WindowManager;
import com.haulmont.cuba.gui.components.AbstractWindow;
import com.haulmont.cuba.gui.components.Button;
import com.haulmont.cuba.gui.components.LookupField;
import com.haulmont.cuba.gui.components.TextField;
import com.haulmont.cuba.gui.data.ValueListener;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Author: Sergey42
 * Date: 01.12.13 17:41
 */
public class CreateBlankFrame extends AbstractWindow {

    @Inject
    protected Button createBlank;
    @Inject
    protected Metadata metadata;
    @Inject
    protected TextField roleTF;
    @Inject
    protected LookupField memberLF;

    protected DefenseDay defenseDay;

    @SuppressWarnings("unchecked")
    @Override
    public void init(Map<String, Object> params) {
        List<CommissionMember> members = (List<CommissionMember>) params.get("members");
        defenseDay = (DefenseDay) params.get("defenseDay");

        memberLF.setOptionsList(members);
        memberLF.addListener(new ValueListener() {
            @Override
            public void valueChanged(Object source, String property, @Nullable Object prevValue, @Nullable Object value) {
                roleTF.setEditable(true);
                CommissionMember member = (CommissionMember) value;
                createBlank.setEnabled(member != null);
                if (member != null) {
                    roleTF.setValue(member.getRole() != null ? member.getRole().getName() : "");
                } else {
                    roleTF.setValue("");
                }
                roleTF.setEditable(false);
            }
        });
    }


    public void createBlank() {
        CommissionMember member = memberLF.getValue();
        List<DefenseDayStudentLink> links = defenseDay.getLinks();

        CommissionMemberBlank blank = metadata.create(CommissionMemberBlank.class);
        blank.setCommissionMember(member);
        blank.setDefenseDay(defenseDay);
        List<Mark> marks = new ArrayList<>(links.size());
        for (DefenseDayStudentLink link : links) {
            Mark mark = metadata.create(Mark.class);
            mark.setBlank(blank);
            mark.setDiplomaStudent(link.getDiplomaStudent());
            marks.add(mark);
        }
        blank.setMarks(marks);

        openEditor("ext$CommissionMemberBlank.edit", blank, WindowManager.OpenType.NEW_TAB);
        close(CLOSE_ACTION_ID, true);
    }
}
